import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { tap } from 'rxjs/operators';
import { SnackbarService, SnackbarType } from '../snackbar.service';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(
    private snackbars: SnackbarService,
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    return next.handle(request).pipe(
      tap({
        error: ({ status, error }: ErrorResponse) => {
          if (status !== 400) {
            return;
          }

          if (error instanceof Blob) {
            const reader = new FileReader();

            reader.addEventListener('loadend', () => {
              this.showError(JSON.parse(reader.result as string));
            });

            reader.readAsText(error);
          } else if (typeof error === 'object') {
            this.showError(error);
          }
        }
      })
    );
  }

  showError(error: ErrorBody) {
    this.snackbars.create(error.detail, SnackbarType.Error);
  }
}

export interface ErrorResponse extends HttpErrorResponse {
  error: ErrorBody | Blob;
}

export interface ErrorBody {
  title: string;

  detail: string;
}
